package com.hk.dao;

import com.hk.entity.Course;
import com.hk.entity.Student;
import com.hk.utils.PropertiesUtils;
import com.mysql.jdbc.Driver;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.util.List;

public class StudentDao {
//    public static void main(String[] args) throws Exception{
//        1.导入驱动jar包
//        2.注册驱动
//        Class.forName("com.mysql.cj.jdbc.Driver");
//        3.获取数据库的链接对象
//        Connection conn= DriverManager.getConnection("jdbc:mysql://localhost:3306/sct","root","wangyiyang520");
//        4.定义sql语句
//        String sql="insert into Student values('1','黄华康','1784','wangyiyang520')";
//        5.获取执行sql的对象，Statement;
//        Statement stmt=conn.createStatement();
//        6.执行sql语句
//        int count=stmt.executeUpdate(sql);
//        7.处理结果
//        System.out.println(count);
//        8.释放资源
//        stmt.close();
//        conn.close();
public void add(Student student) throws Exception {
    QueryRunner queryRunner=new QueryRunner(PropertiesUtils.getDataSource());
    String sql="insert into student(stuName,stuNo,stuPwd) values (?,?,?)";
    queryRunner.update(sql,student.getStuName(),student.getStuNo(),student.getStupwd());
}
    public void delete(Integer cId) throws Exception {
        QueryRunner queryRunner=new QueryRunner(PropertiesUtils.getDataSource());
        String sql="delete from student where cId=?";
        queryRunner.update(sql,cId);
    }
    public void update(Student student) throws Exception {
        QueryRunner queryRunner=new QueryRunner(PropertiesUtils.getDataSource());
        String sql="update student set stuName=?,stuPwd=?where stuId=?";
        queryRunner.update(sql,student.getStuName(),student.getStupwd(),student.getStuId());

    }
    public List<Student> list(Student student) throws Exception {
        QueryRunner queryRunner=new QueryRunner(PropertiesUtils.getDataSource());
        String sql="select * from student";
        List<Student> list=queryRunner.query(sql,new BeanListHandler<>(Student.class));
        return list;
    }
    public Student findById(Integer stuId) throws Exception {
        QueryRunner queryRunner=new QueryRunner(PropertiesUtils.getDataSource());
        String sql="select * from student where stuId=?";
        Student student=queryRunner.query(sql,new BeanHandler<>(Student.class),stuId);
        return student;
    }
    public Student login(String stuNo,String stuPwd) throws Exception {
        QueryRunner queryRunner=new QueryRunner(PropertiesUtils.getDataSource());
        String sql="select * from student where stuNo=? and stuPwd=?";
        Student student=queryRunner.query(sql,new BeanHandler<>(Student.class),stuNo,stuPwd);
        return student;
    }
}
